﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using UOL.PagSeguro.TestServer.Properties;

namespace UOL.PagSeguro.TestServer.UI {
    public partial class Main : Form {

        public delegate void UpdateConsoleEventHandler(string info);
        public event UpdateConsoleEventHandler UpdateConsole;

        public delegate void AddVendaEventHandler(VendaPagSeguro venda);
        public event AddVendaEventHandler AddVenda;

        private IPagSeguroServer _server;

        public Main() {
            InitializeComponent();
            this.UpdateConsole += new UpdateConsoleEventHandler(Main_UpdateConsole);
            this.AddVenda += new AddVendaEventHandler(Main_AddVenda);

            this._server = new PagSeguroServer();
            this._server.OnServerResponse += new OnServerResponseEventHandler(_server_OnServerResponse);
            this._server.OnVendaReceived += new OnVendaReceivedEventHandler(_server_OnVendaReceived);

            this.timer.Start();
        }

        private void startServer() {
            if (!this._server.IsOnline()) {
                if (string.IsNullOrEmpty(Settings.Default.URL_Retorno)) {
                    MessageBox.Show(this, "Informe a URL de retorno antes de iniciar o servidor.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    this.openSettings();
                    return;
                }
                this._server.Start();
                this.btnStartSopServer.Image = Properties.Resources.stop;
            }
        }

        private void stopServer() {
            if (this._server.IsOnline()) {
                this._server.Stop();
                this.btnStartSopServer.Image = Properties.Resources.play;
            }
        }

        private void openSettings() {
            new SettingsForm().ShowDialog(this);
        }

        private void Main_AddVenda(VendaPagSeguro venda) {
            LinhaTabelaVendas linhaNovaVenda = new LinhaTabelaVendas(venda);
            this.linhaTabelaVendasBindingSource.Add(linhaNovaVenda);
            
            new Thread(new ThreadStart(() => {
                this._server.ProcessarRetornoAutomatico(linhaNovaVenda.ToString());
            })).Start();
        }

        private void _server_OnVendaReceived(UOL.PagSeguro.VendaPagSeguro venda) {
            this.Invoke(this.AddVenda, venda);
            this._server_OnServerResponse("Venda " + venda.CodigoReferencia + " de " + venda.Cliente.Nome + " recebida");
        }

        private void Main_UpdateConsole(string info) {
            if (this.console.Text.Length > 0) {
                this.console.Text += System.Environment.NewLine;
            }
            this.console.Text += info;
            this.console.Select(this.console.Text.Length, 0);
            this.console.ScrollToCaret();
        }

        private void _server_OnServerResponse(string request) {
            this.Invoke(this.UpdateConsole, string.Format("[{0}] - {1}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), request));
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e) {
            this._server.Dispose();
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e) {
            this.startServer();
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e) {
            if (this._server.IsOnline()) {
                this._server.Stop();
                this.btnStartSopServer.Image = Properties.Resources.play;
            }
        }

        private void sairToolStripMenuItem_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e) {
            this.openSettings();
        }

        private void btnStartSopServer_Click(object sender, EventArgs e) {
            if (this._server.IsOnline()) {
                this.stopServer();
            } else {
                this.startServer();
            }
        }

        private void btnShowVenda_Click(object sender, EventArgs e) {
            if (this.dataGridView1.SelectedRows.Count > 0) {
                DataGridViewCellEventArgs evtArgs = new DataGridViewCellEventArgs(0, this.dataGridView1.Rows.IndexOf(this.dataGridView1.SelectedRows[0]));
                this.dataGridView1_CellDoubleClick(sender, evtArgs);
            }
        }

        private void timer_Tick(object sender, EventArgs e) {
            this.dataGridView1.DataSource = this.linhaTabelaVendasBindingSource;
            this.dataGridView1.AutoResizeColumns();
        }

        private void sobreToolStripMenuItem1_Click(object sender, EventArgs e) {
            AboutForm form = new AboutForm();
            form.ShowDialog(this);
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            new Thread(new ThreadStart(() => {
                DetalhesVendaForm form = new DetalhesVendaForm(this._server);
                form.LinhaVenda = (LinhaTabelaVendas)this.dataGridView1.Rows[e.RowIndex].DataBoundItem;
                form.ShowDialog();
            })).Start();
        }
    }
}
